use crate::helpers::{get_userpost_id, DatabaseConnection};
use anyhow::Result;
use matrix_sdk::{
    room::Joined,
    ruma::events::room::message::{
        OriginalSyncRoomMessageEvent, Relation, RoomMessageEventContent,
    },
    Client,
};
use std::ops::Deref;

pub async fn show_real_url(
    ev: OriginalSyncRoomMessageEvent,
    _text: String,
    room: Joined,
    _client: Client,
    db: DatabaseConnection,
) -> Result<()> {
    let relation = ev.content.relates_to.unwrap();
    if let Relation::Reply { in_reply_to } = relation {
        let event_id = in_reply_to.event_id.to_string();
        if let Some(userpost_id) = get_userpost_id(event_id, &db).await? {
            db.lock()
                .await
                .deref()
                .query(
                    "update userposts set show_real_url = not show_real_url where id = $1",
                    &[&userpost_id],
                )
                .await?;
            let content = RoomMessageEventContent::text_markdown("toggled show real url");
            room.send(content, None).await.unwrap();
            log::info!("toggled show_real_url on post");
        }
    }
    Ok(())
}
